package xing.application.service.isv.suite;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xing.application.api.DingApi;
import xing.application.service.BaseService;
import xing.domain.isv.suite.CorpJSAPITicket;
import xing.domain.isv.suite.CorpToken;
import xing.repository.isv.suite.CorpJSAPITicketRepository;

import java.util.Calendar;
import java.util.Date;

/********************************
 * 文 件 名 :CorpJSAPITicketService.java
 * 创 建 人：陈天龙
 * 日    期：2017/8/25
 * 描   述：CorpJSAPITicket业务操作
 * 版 本 号：v1.0.0
 ********************************/
@Service
public class CorpJSAPITicketService extends BaseService{

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private CorpJSAPITicketRepository corpJSAPITicketRepository;
    @Autowired
    private CorpTokenService corpTokenService;
    @Autowired
    private DingApi dingApi;

    /**
     * 描    述：获取CorpJSAPITicket
     * 创 建 人：陈天龙
     * 日    期：2017/8/25
     * @param suiteKey
     * @param corpId
     * @return CorpToken
     */
    @Transactional(rollbackFor = Exception.class)
    public CorpJSAPITicket getCorpJSAPITicket(String suiteKey, String corpId) throws Exception{
        logger.info("suiteKey:{},corpId:{}",suiteKey,corpId);
        CorpJSAPITicket corpJSAPITicket = corpJSAPITicketRepository.findBySuiteKeyAndCorpId(suiteKey, corpId);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.MINUTE, 10);//为了防止误差,提前10分钟更新jsticket
        if (null == corpJSAPITicket || calendar.getTime().compareTo(corpJSAPITicket.getExpiredTime()) != -1) {
            CorpToken corpToken = corpTokenService.getCorpToken(suiteKey, corpId);
            CorpJSAPITicket corpJSAPITicketVo = dingApi.getJSTicket(suiteKey,corpId,corpToken.getCorpToken());
            saveOrUpdateCorpJSTicket(corpJSAPITicketVo);
            corpJSAPITicket = corpJSAPITicketVo;
        }
        return corpJSAPITicket;
    }

    /**
     * 描    述：新增或更新corpJSAPITicket
     * 创 建 人：陈天龙
     * 日    期：2017/8/25
     * @param corpJSAPITicket
     */
    private void saveOrUpdateCorpJSTicket(CorpJSAPITicket corpJSAPITicket){
        corpJSAPITicketRepository.saveOrUpdateCorpJSAPITicket(corpJSAPITicket.getId(),corpJSAPITicket.getSuiteKey()
                ,corpJSAPITicket.getCorpId(),corpJSAPITicket.getCorpJsapiTicket()
                ,corpJSAPITicket.getExpiredTime());
    }
}
